import moment from 'moment'
import {
  MACHINE_STATE_MONITOR_TYPE,
  MACHINE_STATE_MINITOR_TIME_UNIT_TYPE
} from '@/utils/constant'
export default {
  data () {
    return {

      cpus: [],
      memories: [],
      disks: [],
      apis: [],

      queryType: MACHINE_STATE_MONITOR_TYPE.MEMORY,
      loading: false,
      ipList: [],
      dataList: [],
      total: 0,
      dataForm: {
        ip: '',
        startDate: '', // new-old-user Date(),
        endDate: '', // new-old-user Date(new-old-user Date().getTime() - 24 * 60 * 60 * 7 * 1000),
        timeUnit: 'hour',
        page: 1,
        limit: 10
      }
    }
  },
  activated () {},

  methods: {
    /**
     * date format
     * */
    todayFormat () {
      return {
        startDate: new Date(new Date().setHours(0, 0, 0)),
        endDate: new Date(),
        timeUnit: 'hour'
      }
    },
    sevenDaysFormat () {
      return {
        startDate: new Date(new Date().getTime() - 24 * 60 * 60 * 7 * 1000),
        endDate: new Date(),
        timeUnit: 'day'
      }
    },

    rightNow () {
      let now = new Date()
      // let oneMinuteBefore = new-old-user Date(new-old-user Date().getTime() - 60 * 1000)
      return {
        startDate: now, // (oneMinuteBefore).format('YYYY-MM-DD HH:mm'),
        endDate: now, // moment(now).format('YYYY-MM-DD HH:mm'),
        timeUnit: 'min'
      }
    },
    /**
     * Pagination
     * */

    pageSizeChangeHandle (val) {
      this.dataForm.page = 1
      this.dataForm.limit = val
      this.reload()
    },
    pageCurrentChangeHandle (val) {
      this.dataForm.page = val
      this.reload()
      // this.getDataList(this.dataForm, this.queryType)
    },

    /**
     * Network events
     * */

    reload () {
      return this.getDataList(this.dataForm, this.queryType)
    },
    loadCpu () {
      return new Promise(resolve => {
        this.getDataList(this.dataForm, MACHINE_STATE_MONITOR_TYPE.CPU).then(
          ({ data: res }) => {
            this.cpus = res.list
            resolve()
          }
        )
      })
    },
    loadMemories () {
      return new Promise(resolve => {
        this.getDataList(this.dataForm, MACHINE_STATE_MONITOR_TYPE.MEMORY).then(
          ({ data: res }) => {
            this.memories = res.list
            resolve()
          }
        )
      })
    },
    loadDisks () {
      return new Promise(resolve => {
        this.getDataList(this.dataForm, MACHINE_STATE_MONITOR_TYPE.DISK).then(
          ({ data: res }) => {
            this.disks = res.list
            resolve()
          }
        )
      })
    },
    loadApis () {
      return new Promise(resolve => {
        this.getDataList(this.dataForm, MACHINE_STATE_MONITOR_TYPE.API).then(
          ({ data: res }) => {
            this.apis = res.list
            resolve()
          }
        )
      })
    },

    getDataList (params, type, handler) {
      // transform params's start Date and end Date by time unit

      let { startDate, endDate, timeUnit } = params

      let format = ''
      Object.keys(MACHINE_STATE_MINITOR_TIME_UNIT_TYPE).map(key => {
        let model = MACHINE_STATE_MINITOR_TIME_UNIT_TYPE[key]
        if (model.key === timeUnit) {
          format = model.format
        }
      })

      startDate = startDate ? moment(startDate).format(format) : ''
      endDate = endDate ? moment(endDate).format(format) : ''

      params = {
        ...params,
        startDate,
        endDate
      }
      this.dataList = []

      switch (type) {
        case MACHINE_STATE_MONITOR_TYPE.CPU:
          return this.getCPUState(params, handler)
        case MACHINE_STATE_MONITOR_TYPE.MEMORY:
          return this.getMemoryState(params, handler)
        case MACHINE_STATE_MONITOR_TYPE.DISK:
          return this.getDiskState(params, handler)
        case MACHINE_STATE_MONITOR_TYPE.API:
          return this.getApiState(params, handler)
      }
    },

    getDiskState (params, handler) {
      /**
       *
       * params: {
            page: 1,
            limit: 1000,
            startDate: '2019-10-10',
            endDate: '2019-12-30',
            timeUnit: 'day',
            ip: this.dataForm.ip
          }

       */
      return new Promise((resolve, reject) => {
        this.loading = true
        this.$http
          .get('/metric/disk/state', {
            params: params
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              reject(res)
              return // this.$message.error(res.msg)
            }

            this.total = res.data.total
            this.dataList = res.data.list.map(item => {
              // item.totalAll = `${item.total / 1024 / 1024}MB`
              item.free_name = `${Number.parseFloat(
                item.free / 1024 / 1024 / 1024
              ).toFixed(2)}GB`
              item.used_name = `${Number.parseFloat(
                item.used / 1024 / 1024 / 1024
              ).toFixed(2)}GB`
              item.used_percent_name = `${Number.parseFloat(
                item.usedPct * 100
              ).toFixed(2)}%`
              return item
            })

            /**
             * free: "467132763511"
             used: "1646649418376"
             usedPct: 0.8206958
             * */

            resolve(res)
          })
          .catch(() => {})
          .finally(() => {
            this.loading = false
          })
      })
    },

    getIpList () {
      this.loading = true

      this.$http
        .get('/monitor/mmonitorapilist/iplist')
        .then(({ data: res }) => {
          this.ipList = res.data.map(item => {
            return { id: item.id, label: item.ip, value: item.ip, ip: item.ip }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    getCPUState (params, handler) {
      return new Promise((resolve, reject) => {
        this.loading = true

        this.$http
          .get('/metric/cpu/state', {
            params: params
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              reject(res)
              return // this.$message.error(res.msg)
            }

            this.total = res.data.total

            this.dataList = res.data.list.map(item => {
              // item.totalAll = `${item.total / 1024 / 1024}MB`
              item.free_percent = `${Number.parseFloat(
                item.systemCpuIdleNormPct * 100
              ).toFixed(2)}%`
              item.used_percent = `${Number.parseFloat(
                item.systemCpuTotalNormPct * 100
              ).toFixed(2)}%`
              return item
            })

            resolve(res)
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    getMemoryState (params, handler) {
      return new Promise((resolve, reject) => {
        this.loading = true
        this.$http
          .get('/metric/memory/state', {
            params: params
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              reject(res)
              return // this.$message.error(res.msg)
            }

            this.total = res.data.total
            this.dataList = res.data.list.map(item => {
              // item.totalAll = `${item.total / 1024 / 1024}MB`
              item.free = `${Number.parseFloat(
                item.actualFree / 1024 / 1024
              ).toFixed(2)}MB`
              item.used = `${Number.parseFloat(
                item.actualUsed / 1024 / 1024
              ).toFixed(2)}MB`
              item.used_percent = `${Number.parseFloat(
                item.actualUsedPct * 100
              ).toFixed(2)}%`
              return item
            })

            /**
             * free: "467132763511"
             used: "1646649418376"
             usedPct: 0.8206958
             * */
            resolve(res)
          })
          .catch(() => {})
          .finally(() => {
            this.loading = false
          })
      })
    },
    getApiState (params, handler) {
      return new Promise((resolve, reject) => {
        this.loading = true
        this.$http
          .get('/metric/api/state', {
            params: params
          })
          .then(({ data: res }) => {
            if (res.code !== 0) {
              reject(res)
              return // this.$message.error(res.msg)
            }

            this.total = res.data.total

            if (handler) {
              this.dataList = handler(res.data.list)
            } else {
              this.dataList = res.data.list
            }

            resolve(res)
          })
          .catch(() => {})
          .finally(() => {
            this.loading = false
          })
      })
    }
  }
}
